package com.yg.ssm.base;

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2016/8/29.
 */
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * @param HttpServletRequest  req
     * @param HttpServletResponse rep
     * @param Oject               o
     * @return boolean ：true 执行后续操作，false，不在执行后续操作
     **/
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse rep, Object o) throws Exception {

        System.out.println("请求拦截器：");
        Cookie[] cok = req.getCookies();

        String sid = "";
        for (Cookie ck : cok) {

            if (ck.getName().equals("sid")) {
                sid = ck.getValue();
            }
        }
        if ("".equals(sid) || req.getSession().getAttribute(sid) == null || !req.getSession().getId().equals(sid)) {
            req.setAttribute("msg", "authValid");
            req.getRequestDispatcher("/").forward(req, rep);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
